/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  if (!time) return ''
  const format = cFormat || 'yyyy-mm-dd hh:ii:ss'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/(y|m|d|h|i|s|a)+/gi, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') { return ['一', '二', '三', '四', '五', '六', '日'][value - 1] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

export function isJSON(val) {
  if (typeof val !== 'string') {
    return false
  }
  try {
    const obj = JSON.parse(val)
    if (Object.prototype.toString.call(obj) === '[object Object]') {
      return true
    } else {
      return false
    }
  } catch (e) {
    return false
  }
}

export function deepClone(o, c) {
  const toString = Object.prototype.toString
  toString.call(o) === '[object Array]' ? (c = c || []) : (c = c || {})
  for (const i in o) {
    if (typeof o[i] === 'object') {
      // 要考虑深复制问题了
      if (Array.isArray(o[i])) {
        // 这是数组
        c[i] = []
      } else {
        // 这是对象
        c[i] = {}
      }
      deepClone(o[i], c[i])
    } else {
      c[i] = o[i]
    }
  }
  return c
}

export function ext() {
  // eslint-disable-next-line
  var target = arguments[0] || {},
    i = 1,
    length = arguments.length,
    deep = false,
    options,
    name,
    src,
    copy
  if (typeof target === 'boolean') {
    deep = target
    target = arguments[1] || {}
    i = 2
  }
  if (typeof target !== 'object' && typeof target !== 'function') {
    target = {}
  }
  if (length === i) {
    target = this
    --i
  }
  for (; i < length; i++) {
    if ((options = arguments[i]) != null) {
      for (name in options) {
        src = target[name]
        copy = options[name]
        if (target === copy) {
          continue
        }
        if (
          deep &&
          copy &&
          (typeof copy === 'object' || Array.isArray(copy)) &&
          !copy.nodeType
        ) {
          var clone =
            src && (typeof src === 'object' || Array.isArray(src))
              ? src
              : Array.isArray(copy)
                ? []
                : {}
          target[name] = ext(deep, clone, copy)
        } else if (copy !== undefined) {
          target[name] = copy
        }
      }
    }
  }
  return target
}

// 无树状结构数组转换树状节点方法
export function arrayToTree(
  treeArray,
  idKey = 'id',
  pidKey = 'pid',
  childrenKey = 'children'
) {
  const r = []
  const tmpMap = {}
  treeArray = deepClone(treeArray)

  for (let i = 0, l = treeArray.length; i < l; i++) {
    // 以每条数据的id作为obj的key值，数据作为value值存入到一个临时对象里面
    tmpMap[treeArray[i][idKey]] = treeArray[i]
  }

  for (let j = 0, l = treeArray.length; j < l; j++) {
    const key = tmpMap[treeArray[j][pidKey]]

    // 循环每一条数据的pid，假如这个临时对象有这个key值，就代表这个key对应的数据有children，需要Push进去
    if (key) {
      if (!key[childrenKey]) {
        key[childrenKey] = [treeArray[j]]
      } else {
        const obj = {}
        const bindArr = [...key[childrenKey], treeArray[j]]
          .sort(item => item[childrenKey])
          .reverse()
        key[childrenKey] = bindArr.reduce((cur, next) => {
          obj[next[idKey]] ? '' : (obj[next[idKey]] = true && cur.push(next))
          return cur
        }, [])
      }
    } else {
      // 如果没有这个Key值，那就代表没有父级,直接放在最外层
      r.push(treeArray[j])
    }
  }
  return r
}

export function findValByKey(data, val, key = 'id', childrenKey = 'children') {
  for (const i in data) {
    if (data[i][key] && data[i][key] === val) {
      return data[i]
    }
    if (data[i][childrenKey] && data[i][childrenKey].length) {
      var result = findValByKey(data[i][childrenKey], val, key, childrenKey)
      if (result !== undefined) return result
    }
  }
}

export function createDownloadLink(res = {}) {
  const downloadLink = window.document.createElement('a')
  const fileName =
    (res.headers &&
      res.headers.hasOwnProperty('content-disposition') &&
      res.headers['content-disposition'].match(/filename="(.+)"/) &&
      res.headers['content-disposition'].match(/filename="(.+)"/)[1]) ||
    res.headers['content-disposition'].split('filename=')[1]
  const fileUrl = res.data && window.URL.createObjectURL(res.data)
  downloadLink.href = fileUrl
  downloadLink.download = decodeURI(fileName)
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)
  window.URL.revokeObjectURL(fileUrl)
}

// export function loadComponent(url) {
//   if (process.env.NODE_ENV === 'development') {
//     return require('@/views' + url).default
//   } else {
//     return () => import('@/views' + url)
//   }
// }

/**
 * Remove an item from an array
 */
export function remove(arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}
